﻿CREATE PROCEDURE [dbo].[CustomerReturnLinesInsert]
(--возврат от покупателя
	@DocId int,
	@ReturnLineId int, --идентификатор возвращяемой строки приходного документа
	@Qntty int,
	@RetailSum decimal(19, 2),
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50)
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int, @intNextId int
DECLARE @intDocTypeId int, @intDocContragentId int, @intReturnQntty int, @intAlreadyQntty int
DECLARE @datDocDate smalldatetime, @datReturnDocDate smalldatetime
--DECLARE @intInputLineId int, @intInputDocId int
DECLARE @PartyId int --идентификатор возвращяемой партии.

SET NOCOUNT ON
IF (@DocId Is Null) OR (@ReturnLineId Is Null) OR (@Qntty Is Null) OR (@RetailSum Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF (@Qntty <=0) OR (@RetailSum <=0)
BEGIN
	SELECT @intErrCode = 2, @strMsg = 'Количество и сумма д.б. больше нуля!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @intDocTypeId = DocTypeId, @datDocDate = DocDate
FROM [CA].[Documents] WHERE Id = @DocId
IF (@intDocTypeId Is Null)
BEGIN
	SELECT @intErrCode = 3, @strMsg = 'Не найден документ с идентификатором ' + cast(@DocId as varchar(20)) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF (@intDocTypeId <> 7)
BEGIN
	SELECT @intErrCode = 4, @strMsg = 'Неправильный тип документа с идентификатором ' + cast(@DocId as varchar(20)) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF EXISTS (SELECT * FROM CA.GoodsDocLines WHERE DocId = @DocId AND ReturnLineId = @ReturnLineId )
BEGIN
	SELECT @intErrCode = 5, 
	@strMsg = 'Дублируется строка возвращяемого документа!'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

SELECT @intDocContragentId = D.ContragentId, @datReturnDocDate = D.DocDate, -- D.Id, D.DocTypeId,
@PartyId = L.PartyId, @intReturnQntty = -L.Qntty
FROM  CA.GoodsDocLines AS L INNER JOIN CA.Documents AS D ON L.DocId = D.Id
WHERE L.Id = @ReturnLineId

IF (@intDocContragentId Is Null)
BEGIN
	SELECT @intErrCode = 6, @strMsg = 'Не указан контрагент в документе с идентификатором ' + cast(@DocId as varchar(20)) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF @datDocDate < @datReturnDocDate 
BEGIN
	SELECT @intErrCode = 7, @strMsg = 'Дата приходного документа меньше даты расходного документа!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @intAlreadyQntty = sum(L.Qntty) --уже возвращено
FROM  CA.GoodsDocLines AS L INNER JOIN CA.Documents AS D ON L.DocId = D.Id
WHERE D.DocTypeId = 7 AND L.ReturnLineId = @ReturnLineId

IF (@Qntty + IsNull(@intAlreadyQntty, 0))> @intReturnQntty
BEGIN
	SELECT @intErrCode = 8, 
	@strMsg = 'Возвращенное количество больше проданного количества!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT
--получение значения идентификатора
EXEC @intRet = dbo.GetNextCounterFor 'GoodsLines', @intNextId OUTPUT
IF @intRet <> 0 RETURN @intRet

	SET NOCOUNT OFF;
INSERT INTO [CA].[GoodsDocLines] (Id, [DocId], [PartyId], [Qntty], [RetailSum], ReturnLineId, [Note], [MD], [MW]) 
VALUES ( @intNextId, @DocId, @PartyId, @Qntty, @RetailSum, @ReturnLineId, @Note, @MD, @MW);

SELECT L.Id, L.DepartmentId, L.DocId, L.PartyId, 
L.Qntty, L.RetailSum, L.ReturnLineId,
L.Note, L.MD, L.MW 
FROM CA.GoodsDocLines AS L WHERE L.Id = @intNextId

RETURN 0